import java.util.Arrays;

/**
 * Created by zhourh on 2018/6/13.
 *
 * 给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。

 找到给定的二维数组中最大的岛屿面积。(如果没有岛屿，则返回面积为0。)

 示例 1:

 [[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]
 对于上面这个给定矩阵应返回 6。注意答案不应该是11，因为岛屿只能包含水平或垂直的四个方向的‘1’。

 示例 2:

 [[0,0,0,0,0,0,0,0]]
 对于上面这个给定的矩阵, 返回 0。

 注意: 给定的矩阵grid 的长度和宽度都不超过 50。

 dfs

 */
public class MaxAreaOfIsland {

    public static void main(String[] args) {
        int[][] grid = new int[][]{ {0,0,1,0,0,0,0,1,0,0,0,0,0},
                                    {0,0,0,0,0,0,0,1,1,1,0,0,0},
                                    {0,1,1,0,1,0,0,0,0,0,0,0,0},
                                    {0,1,0,0,1,1,0,0,1,0,1,0,0},
                                    {0,1,0,0,1,1,0,0,1,1,1,0,0},
                                    {0,0,0,0,0,0,0,0,0,0,1,0,0},
                                    {0,0,0,0,0,0,0,1,1,1,0,0,0},
                                    {0,0,0,0,0,0,0,1,1,0,0,0,0}};
        System.out.println(new MaxAreaOfIsland().maxAreaOfIsland(grid));
    }

    public int maxAreaOfIsland(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }

        int height = grid.length;
        int width = grid[0].length;

        int maxArea = 0;

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (grid[i][j] == 1) {
                    maxArea = Math.max(maxArea, areaOfIsland(grid, i, j));
                }
            }
        }

        return maxArea;
    }

    public int areaOfIsland(int[][] grid, int x, int y) {
        int height = grid.length;
        int width = grid[0].length;

        int area = 1;

        grid[x][y] = 0;

        int[][] dir = new int[][]{{-1,0}, {1,0}, {0,-1}, {0,1}};
        for (int i = 0;i < dir.length; i++) {
            int x0 = x + dir[i][0];
            int y0 = y + dir[i][1];
            if (x0 >=0 && x0 < height && y0 >= 0 && y0 < width && grid[x0][y0] == 1) {
                area += areaOfIsland(grid, x0, y0);
            }
        }

        return area;
    }
}
